<template>
	<div>
		<vee-observer v-slot="{invalid, validate}">
			<form @submit.prevent="validate().then(updateProfile)">
				<div class="form-group row">
					<label for="name" class="col-md-3 col-form-label text-md-right">用户名</label>

					<div class="col-md-7">
						<vee-validator name="用户名" rules="required|min:2|max:32" v-slot="{errors}">
							<input
								id="name"
								type="text"
								class="form-control"
								v-model="name"
								required
								autocomplete="name"
								autofocus
								:class="{'is-invalid': errors[0]}"
							>
							<span v-show="errors[0]" class="invalid-feedback" role="alert">
								<strong>{{errors[0]}}</strong>
							</span>
						</vee-validator>
					</div>
				</div>

				<div class="form-group row">
					<label for="email" class="col-md-3 col-form-label text-md-right">邮箱</label>

					<div class="col-md-7">
						<vee-validator name="邮箱" rules="required|email" v-slot="{errors}">
							<input
								id="email"
								type="email"
								class="form-control"
								v-model="email"
								required
								autocomplete="email"
								:class="{'is-invalid':errors[0]}"
							>

							<span v-show="errors[0]" class="invalid-feedback" role="alert">
								<strong>{{errors[0]}}</strong>
							</span>
						</vee-validator>
					</div>
				</div>

				<div class="form-group row mb-0">
					<div class="col-md-7 offset-md-3">
						<button type="submit" class="btn btn-primary" :disabled="invalid">保存修改</button>
						<button class="btn btn-secondary" @click="cancel">取消修改</button>
					</div>
				</div>
			</form>
		</vee-observer>
	</div>
</template>

<script>
export default {
	computed: {
		name: {
			get() {
				return this.$store.state.AuthUser.name;
			},
			set(value) {
				this.$store.commit("setUserName", value);
			}
		},
		email: {
			get() {
				return this.$store.state.AuthUser.email;
			},
			set(value) {
				this.$store.commit("setUserEmail", value);
			}
		}
	},
	methods: {
		updateProfile() {
			let formData = {
				name: this.name,
				email: this.email
			};
			this.$store.dispatch("updateProfileRequest", formData).then(res => {
				this.$router.push({ name: "profile" });
			});
		},
		cancel() {
			this.$router.push({ name: "profile" });
		}
	}
};
</script>

<style lang="scss" scoped>
</style>
